package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;
import service.LoginService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/login")
public class loginControllor  {

    @Reference
    private LoginService loginService;

    @Autowired
    private JedisPool jedisPool;

    //使用手机号和验证码登录
    @RequestMapping("/check")
    public Result check( HttpServletResponse httpServletResponse ,@RequestBody Map map) {


        try {
            //检查验证码和redis的一致不
            String validateCode = (String) map.get("validateCode");
            String telephone = (String) map.get("telephone");
            String validateCode_redis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
            //if (validateCode_redis!=validateCode){
            if (validateCode==null || validateCode_redis==null || !validateCode_redis.equals(validateCode)){
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }

            //一致,则根据号码查询是不是会员,不是会员则注册为会员
            Member member = loginService.findByPhone(telephone);
            if (member==null){
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                loginService.save(member);
            }

            //保存用户登录状态
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            httpServletResponse.addCookie(cookie);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);

            return new Result(true,MessageConstant.LOGIN_SUCCESS);



        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "登录失败");

        }

    }
}